package com.tueye.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tueye.base.util.Page;
import com.tueye.entity.Admin;
import com.tueye.entity.KeyWords;
import com.tueye.service.IKeyWordService;
import com.tueye.utils.BusinessDetail;
import com.tueye.utils.BusinessDetailHelper;
import com.tueye.utils.DateUtils;
import com.tueye.utils.UUIDGenerator;

/**
 * 关键字操作
 * 
 * @author hanxiaowei
 * 
 */
@SuppressWarnings("unchecked")
@org.springframework.stereotype.Controller
@RequestMapping("/keyWord.do")
public class KeyWordController {
	private Log log = LogFactory.getLog(KeyWordController.class);
	@Autowired
	@Qualifier("keyWordService")
	private IKeyWordService keyWordService;

	@RequestMapping(params = "method=standGridQuery")
	public String PageShow(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// js传过来的参数列表：
		// page:页数
		// rp:每页显示多少条
		// sortname：排序的字段名称
		// sortorder: 排序的方向；比如：asc，desc；
		// query : 查询的条件
		// qtype ：查询的类型

		String rp = request.getParameter("rp"); // 每页显示的数据数
		String pageString = request.getParameter("page");// 获取
															// flexgrid传过来的页数。
		String query = request.getParameter("query");// 获取 查询的条件
		query = java.net.URLDecoder.decode(query, "UTF-8");// 解码

		String qtype = request.getParameter("qtype");// 获取 查询的类型
		String sortorder = request.getParameter("sortorder");// 获取 查询的类型
		if (pageString == null || pageString.length() == 0) {
			pageString = "1";
		}
		StringBuffer hql = new StringBuffer(" from com.tueye.entity.KeyWords ");
		if (StringUtils.isNotEmpty(query))
			hql.append(" where " + query);
		// if(StringUtils.isNotEmpty(query)) hql.append(" where "+qtype+"
		// ='"+query+"'");
		if (StringUtils.isNotEmpty(qtype))
			hql.append("   order   by " + qtype);
		if (StringUtils.isNotEmpty(sortorder))
			hql.append("   " + sortorder);
		System.out.println("##########hql:" + hql.toString());
		Page pageModel = keyWordService.pagedQueryByHQL(hql.toString(), Integer
				.valueOf(pageString), Integer.valueOf(rp), null);

		Map pageInfo = new HashMap();
		pageInfo.put("page", new Integer(pageString));
		pageInfo.put("total", pageModel.getTotalCount());
		// 生成json字符串
		String jsonStr = getJsonString((List) pageModel.getResult(), pageInfo);
		log.info("###############:" + jsonStr);
		response.setContentType("html/txt");
		response.setCharacterEncoding("utf-8");
		response.getWriter().println(jsonStr);

		return null;
	}

	@RequestMapping(params = "action=save")
	public String save(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF-8");
			BusinessDetail bd = BusinessDetailHelper.getBusDetailInfo(request);
			String keyword_name = (String) request.getParameter("keyword_name");
			// 新增
			KeyWords keyWord = new KeyWords();
			keyWord.setId(new UUIDGenerator().getUUID());
			keyWord.setKeyword_name(keyword_name);
			keyWord.setSys_time(bd.getSys_time());
			keyWord.setSys_fille(bd.getSys_loginName());
			keyWordService.addKeyWord(keyWord);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}
	
	/**
	 * type表示操作类型
	 * new/null 新建
	 * maindi != null 并且type =copy  复制
	 * maindi != null 并且type =edit  修改
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "action=saveDetail")
	public String saveDetail (HttpServletRequest request, HttpServletResponse response) throws Exception {
			try{
				request.setCharacterEncoding("UTF-8");
				BusinessDetail bd = BusinessDetailHelper.getBusDetailInfo(request);
				String mainId = (String) request.getParameter("id");
				String type = (String)request.getParameter("type");
				String keyword_name = (String) request.getParameter("keyword_name");
				//修改
				if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("edit")){
					KeyWords keyWord = new KeyWords();
					keyWord = this.keyWordService.getKeyWordsById(mainId);
					keyWord.setKeyword_name(keyword_name);
					keyWord.setSys_time(bd.getSys_time());
					keyWord.setSys_fille(bd.getSys_loginName());
					keyWordService.addKeyWord(keyWord);
				}else{
					//复制
					if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("copy")){
						KeyWords keyWord = new KeyWords();
						keyWord = this.keyWordService.getKeyWordsById(mainId);
						keyWord.setId(new UUIDGenerator().getUUID());
						keyWord.setKeyword_name(keyword_name);
						keyWord.setSys_time(bd.getSys_time());
						keyWord.setSys_fille(bd.getSys_loginName());
						keyWordService.addKeyWord(keyWord);
					}else{
						// 新增
						KeyWords keyWord = new KeyWords();
						keyWord.setId(new UUIDGenerator().getUUID());
						keyWord.setKeyword_name(keyword_name);
						keyWord.setSys_time(bd.getSys_time());
						keyWord.setSys_fille(bd.getSys_loginName());
						keyWordService.addKeyWord(keyWord);
					}
				}
				response.getWriter().print("true");
			}catch (RuntimeException e) {
				log.error(e.getMessage());
			}
			
		return null;
	}
	
	@RequestMapping(params = "action=initDetail")
	public ModelAndView initDetail (HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String mainId = (String) request.getParameter("id");
		String type = (String)request.getParameter("type");
		ModelAndView mav = new ModelAndView("/pages/admin/keyword/addKeyWord");
		KeyWords keyWords = new KeyWords();
		//修改
		if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("edit")){
			keyWords = keyWordService.getKeyWordsById(mainId);
			request.setAttribute("keyWord", keyWords);
			request.setAttribute("type", type);
		}else{
			//复制
			if(StringUtils.isNotEmpty(mainId)&&type.toLowerCase().equalsIgnoreCase("copy")){
				keyWords = keyWordService.getKeyWordsById(mainId);
				keyWords.setId(null);
				request.setAttribute("keyWord", keyWords);
				request.setAttribute("type", type);
			}else{
				//新增
				keyWords = new KeyWords();
			}
		}
		return mav;
	}

	@RequestMapping(params = "action=delete")
	public void delete(HttpServletRequest request, HttpServletResponse response) {

		String retult = "true";
		try {
			request.setCharacterEncoding("UTF-8");
			String id = request.getParameter("id");
			keyWordService.delKeyWords(id);
			response.getWriter().print("true");
		} catch (Exception e) {
			log.error("#####出错了" + e.getMessage());

		}

	}

	/**
	 * @param list
	 * @param pageInfo
	 * @return
	 */
	private String getJsonString(List list, Map pageInfo) {

		List mapList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			KeyWords keyWord = (KeyWords) list.get(i);
			Map cellMap = new HashMap();
			cellMap.put("numid", i + 1);
			cellMap.put("cell", new Object[] {

					keyWord.getId(),
					i + 1,
					StringUtils.isEmpty(keyWord.getKeyword_name())?"":keyWord.getKeyword_name(),
					keyWord.getKeyword_clickNum() ,
					StringUtils.isEmpty(keyWord.getSys_fille())?"":keyWord.getSys_fille(),
					DateUtils.getDate2Str("yyyy-MM-dd HH:mm", keyWord
							.getSys_time()) });
			mapList.add(cellMap);
		}
		pageInfo.put("rows", mapList);
		com.tueye.ajax.json.JSONObject object = new com.tueye.ajax.json.JSONObject(
				pageInfo);
		return object.toString();
	}

}
